package csu.web.mypetstore.filter;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.History;
import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.domain.Product;
import csu.web.mypetstore.persistence.AccountDao;
import csu.web.mypetstore.persistence.impl.AccountDaoImpl;
import csu.web.mypetstore.service.CatalogService;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class FilterA implements Filter{
    private CatalogService catalogService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("过滤器开始执行");
        //执行目标servlet

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String itemId=req.getParameter("itemId");
        catalogService=new CatalogService();
        Item item=catalogService.getItem(itemId);
        Product product=item.getProduct();

        HttpSession session=req.getSession();

        String isAdd=null;
        session.setAttribute("isAdd","true");

//添加日志功能

        session.setAttribute("product", product);
        session.setAttribute("item", item);

        String productName=product.getName();
        String itemName=item.getItemId();

        Account account = (Account) session.getAttribute("loginAccount");
        AccountDao accountDao=new AccountDaoImpl();



        if(account!=null){
            boolean history=accountDao.findHistoryByUsernameandCategory(account.getUsername(),itemName);

            History history1=accountDao.getHistoryByUsername(account.getUsername(),itemName);
            if(!history || history1.getVisittimes()==0){//找不到时
                accountDao.insertHistroyUserId(account,itemName);
                accountDao.InitVisitNum(account,itemName);
                accountDao.initCartVisitNum(account,itemName);
                accountDao.insertHistroyUser(account,itemName);
                accountDao.UpdateVisitNum(account,itemName);

            }else{
                accountDao.UpdateVisitNum(account,itemName);
            }
        }




        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("过滤器结束执行");
    }

    @Override
    public void destroy() {
    }
}
